<?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property string $user_id
 * @property string $username
 * @property string $email
 * @property string $first_name
 * @property string $last_name
 * @property string $token
 * @property integer $is_active
 * @property string $created_at
 * @property string $is_admin
 *
 * The followings are the available model relations:
 * @property Meme[] $memes
 */
class User extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'user';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username,password', 'required'),
            array('is_active', 'numerical', 'integerOnly' => true),
            array('username', 'length', 'max' => 100),
            array('email, first_name, last_name', 'length', 'max' => 255),
            array('token', 'length', 'max' => 32),
            array('created_at, is_admin', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('user_id, username, email, first_name, last_name, token, is_active, created_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'memes' => array(self::HAS_MANY, 'Meme', 'user_fk'),
            'profiles' => array(self::HAS_MANY, 'SocialLogin', 'user_fk'),
            'likes' => array(self::HAS_MANY, 'MemeLike', 'user_fk'),
            'followers' => array(self::HAS_MANY, 'UserFollow', 'following_id'),
            'followings' => array(self::HAS_MANY, 'UserFollow', 'user_fk'),
            'flags' => array(self::HAS_MANY, 'MemeFlag', 'user_fk'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'user_id' => Yii::t('yii', 'Id User'),
            'username' => Yii::t('yii', 'Username'),
            'email' => Yii::t('yii', 'Email'),
            'first_name' => Yii::t('yii', 'First Name'),
            'last_name' => Yii::t('yii', 'Last Name'),
            'token' => Yii::t('yii', 'Token'),
            'is_active' => Yii::t('yii', 'Is Active'),
            'created_at' => Yii::t('yii', 'Created At'),
            'is_admin' => Yii::t('yii', 'Is Admin'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('user_id', $this->user_id, true);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('first_name', $this->first_name, true);
        $criteria->compare('last_name', $this->last_name, true);
        $criteria->compare('token', $this->token, true);
        $criteria->compare('is_active', $this->is_active);
        $criteria->compare('created_at', $this->created_at, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function loadLikesToSession() {
        $likes = MemeLike::model()->findAllByAttributes(array('user_fk' => Yii::app()->user->id));
        $user_likes = array();
        foreach ($likes as $like) {
            $user_likes[] = $like->meme_fk;
        }
        Yii::app()->session[Meme::LIKE_KEY] = $user_likes;
    }

    /**
     * Returns User model by its email
     * 
     * @param string $email 
     * @access public
     * @return User
     */
    public function findByEmail($email) {
        return self::model()->findByAttributes(array('email' => $email));
    }
    
    public function getTop_users() {
        
        $q = new CDbCriteria(array(
                    'join' => 'INNER JOIN meme m ON m.user_fk = t.user_id',
                    'group' => 'm.user_fk',
                    'order' => 'COUNT(m.user_fk) DESC',
                    'condition' => 't.is_active = 1',
                    'limit' => 10,
                ));
        
        return User::model()->findAll($q);
    }
    
    public static function follow($user_fk) {
        if(
            User::model()->exists('user_id = :user_fk', array(':user_fk' => $user_fk)) &&
            !UserFollow::model()->exists('user_fk = :user_id AND following_id = :following_id', array(':user_id' => Yii::app()->user->id, ':following_id' => $user_fk))
        ) {
            $userFollow = new UserFollow();
            $userFollow->user_fk = Yii::app()->user->id;
            $userFollow->following_id = $user_fk;
            $userFollow->created_at =  new CDbExpression('NOW()');
            $userFollow->save();
            Yii::app()->plugin->onUserFollow(new CEvent($userFollow));
            return self::model()->findByPk($user_fk);
        }
        return false;
    }
    
    public static function unfollow($user_fk) {
        if(
            $userFollow = UserFollow::model()->findByAttributes(array('user_fk' => Yii::app()->user->id, 'following_id' => $user_fk))
        ) {
            Yii::app()->plugin->onUserUnFollow(new CEvent($userFollow));
            $userFollow->delete();
            return self::model()->findByPk($user_fk);
        }
        return false;
    }
    
    public static function isFollowing($user_fk) {
        return UserFollow::model()->findByAttributes(array('user_fk' => Yii::app()->user->id, 'following_id' => $user_fk));
    }
    
    public function scopes() {
        return array(
            'visible' => array(
                'condition' => 'user.is_active',
            ),
        );
    }
    
    public function afterDelete() {
        $memeLikes = MemeLike::model()->findAllByAttributes(array('user_fk' => $this->user_id));
        if ($memeLikes) {
            foreach ($memeLikes as $memeLike) {
                $memeLike->delete();
            }
        }
        
        $memes = Meme::model()->findAllByAttributes(array('user_fk' => $this->user_id));
        if ($memes) {
            foreach ($memes as $meme) {
                $meme->delete();
            }
        }
        
        $follows = UserFollow::model()->findAll('following_id = :following_id OR user_fk = :user_fk', array(':user_fk' => $this->user_id, ':following_id' => $this->user_id));
        if ($follows) {
            foreach ($follows as $follow) {
                $follow->delete();
            }
        }
        
        $logins = SocialLogin::model()->findAllByAttributes(array('user_fk' => $this->user_id));
        if ($logins) {
            foreach ($logins as $login) {
                $login->delete();
            }
        }
        
        return parent::afterDelete();
    }
}